package com.zzw.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzw.springboot.annotation.Log;
import com.zzw.springboot.bean.SysRole;
import com.zzw.springboot.service.SysRoleService;
import com.zzw.springboot.util.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 角色管理控制器
 */
@Api(tags = "角色管理接口")
@Slf4j
@RestController
@RequestMapping("/system/role")
public class SysRoleController {

    @Autowired
    private SysRoleService roleService;

    /**
     * 获取角色列表
     */
    @ApiOperation("获取角色列表")
    @GetMapping("/list")
    public Result list(SysRole role,
                      @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                      @RequestParam(value = "pageSize", required = false, defaultValue = "10") Integer pageSize) {
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = buildQueryWrapper(role);
        Page<SysRole> page = roleService.page(new Page<>(pageNum, pageSize), lambdaQueryWrapper);
        log.info("page={}", page);
        return Result.success(page);
    }

    /**
     * 构建查询条件
     */
    private LambdaQueryWrapper<SysRole> buildQueryWrapper(SysRole role) {
        LambdaQueryWrapper<SysRole> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysRole::getIsDeleted, 0);

        if (role != null) {
            if (StringUtils.hasText(role.getRoleName())) {
                queryWrapper.like(SysRole::getRoleName, role.getRoleName());
            }
            if (StringUtils.hasText(role.getRoleCode())) {
                queryWrapper.like(SysRole::getRoleCode, role.getRoleCode());
            }
            if (role.getStatus() != null) {
                queryWrapper.eq(SysRole::getStatus, role.getStatus());
            }
        }

        // 按排序字段升序
        queryWrapper.orderByAsc(SysRole::getSort);
        return queryWrapper;
    }

    /**
     * 根据角色ID获取详细信息
     */
    @ApiOperation("根据角色ID获取详细信息")
    @GetMapping("/{roleId}")
    public Result getInfo(@PathVariable Integer roleId) {
        return Result.success(roleService.selectRoleById(roleId));
    }

    /**
     * 新增角色
     */
    @ApiOperation("新增角色")
    @Log(module = "角色管理", type = "新增", description = "新增角色")
    @PostMapping
    public Result add(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return Result.error("新增角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        if (!roleService.checkRoleCodeUnique(role)) {
            return Result.error("新增角色'" + role.getRoleName() + "'失败，角色编码已存在");
        }
        return Result.success(roleService.insertRole(role));
    }

    /**
     * 修改角色
     */
    @ApiOperation("修改角色")
    @Log(module = "角色管理", type = "修改", description = "修改角色")
    @PutMapping
    public Result edit(@Validated @RequestBody SysRole role) {
        if (!roleService.checkRoleNameUnique(role)) {
            return Result.error("修改角色'" + role.getRoleName() + "'失败，角色名称已存在");
        }
        if (!roleService.checkRoleCodeUnique(role)) {
            return Result.error("修改角色'" + role.getRoleName() + "'失败，角色编码已存在");
        }

        return Result.success(roleService.updateRole(role));
    }

    /**
     * 角色状态修改
     */
    @ApiOperation("角色状态修改")
    @Log(module = "角色管理", type = "修改状态", description = "修改角色状态")
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysRole role) {
        return Result.success(roleService.updateRoleStatus(role));
    }

    /**
     * 角色数据权限修改
     */
    @ApiOperation("角色数据权限修改")
    @Log(module = "角色管理", type = "修改数据权限", description = "修改角色数据权限")
    @PutMapping("/dataScope")
    public Result dataScope(@RequestBody SysRole role) {
        return Result.success(roleService.authDataScope(role));
    }

    /**
     * 删除角色
     */
    @ApiOperation("删除角色")
    @Log(module = "角色管理", type = "删除", description = "删除角色")
    @DeleteMapping("/{roleId}")
    public Result remove(@PathVariable Integer roleId) {
        try {
            return Result.success(roleService.deleteRoleById(roleId));
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 批量删除角色
     */
    @ApiOperation("批量删除角色")
    @Log(module = "角色管理", type = "批量删除", description = "批量删除角色")
    @DeleteMapping("/batch/{roleIds}")
    public Result batchRemove(@PathVariable Integer[] roleIds) {
        try {
            return Result.success(roleService.deleteRoleByIds(roleIds));
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }

    /**
     * 获取角色选择框列表
     */
    @ApiOperation("获取角色选择框列表")
    @GetMapping("/optionList")
    public Result optionList() {
        SysRole role = new SysRole();
        role.setStatus(1); // 只查询正常状态的角色
        LambdaQueryWrapper<SysRole> lambdaQueryWrapper = buildQueryWrapper(role);
        List<SysRole> roles = roleService.list(lambdaQueryWrapper);
        return Result.success(roles);
    }

    /**
     * 导出角色数据
     */
    @ApiOperation("导出角色数据")
    @Log(module = "角色管理", type = "导出", description = "导出角色数据")
    @PostMapping("/export")
    public void export(HttpServletResponse response, @RequestBody(required = false) List<Integer> roleIds) throws IOException {
        roleService.exportRole(response, roleIds);
    }
}
